package org.geektimes.include;

import org.geektimes.injection.context.ComponentContext;
import org.geektimes.injection.context.Initializer.IncludeComponentInitializer;
import org.geektimes.projects.user.domain.User;
import org.geektimes.projects.user.management.UserManager;

import javax.management.*;
import java.lang.management.ManagementFactory;

/**
 * @FileName: JmxComponentInitializer
 * @Description: TODO
 * @Author: MaWenHao
 * @Created: 2021/3/17 - 下午8:49
 */
public class JmxComponentInitializer implements IncludeComponentInitializer {
    /**
     * 初始化MBean
     *
     * @param componentContext
     */
    @Override
    public void init(ComponentContext componentContext) {
        // 获取平台 MBean Server
        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        // 创建 UserMBean 实例
        User user = new User();
        user.setId(123L);
        user.setName("刘备");
        user.setPassword("123456");
        try {
            // 为 UserMXBean 定义 ObjectName
            ObjectName objectName = new ObjectName("org.geektimes.projects.user.management:type=User");
            mBeanServer.registerMBean(new UserManager(user), objectName);
        } catch (InstanceAlreadyExistsException e) {
            e.printStackTrace();
        } catch (MBeanRegistrationException e) {
            e.printStackTrace();
        } catch (NotCompliantMBeanException e) {
            e.printStackTrace();
        } catch (MalformedObjectNameException e) {
            e.printStackTrace();
        }
    }

    /**
     * 组件 销毁方法
     *
     * @param componentContext
     */
    @Override
    public void destroy(ComponentContext componentContext) {
    }
}
